<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\IndexApi;
use App\Http\Controllers\Api\HomeGoodsSaleApi;
use App\Http\Controllers\Home\ShowLinksController;
use App\Model\Goodssale;
use App\Model\Goods;
use App\Http\Controllers\Api\SearchApi;
use Illuminate\Support\Facades\Redis;
use DB;

class HomeGoodsSaleController extends Controller
{
   	/**
   	 * 显示商品促销页
   	 */
   	public function HomeGoodsSale()
   	{
   		$index = new IndexApi();

   		//查询站点信息
    	$sate = IndexApi::getSate();

      //查询友情链接数据
      $link = new ShowLinksController;
      $linksArray = $link->index();

    	//查询父级分类信息
      $types = $index->getTypes();

      $goodssale = new HomeGoodsSaleApi();

      //查询促销商品
      $sales = $goodssale->getGoodsSale();

      //实例化搜索类
      $search = new SearchApi('abc');

        //查询热搜词
      $Hotsearch = $search->getHot();

      //查询促销表
      $sale = Goodssale::select('id', 'goods_id', 'start_time', 'end_time', 'status')->get()->toArray();

      foreach ($sale as $v) {

        //判断是否已经过了促销时间
        if ($v['end_time'] < date('Y-m-d H:i:s')) {

          //把商品表促销状态改为否
          Goods::where('id', $v['goods_id'])->update(['promate' => 0]);

          //删除促销信息
          Goodssale::where('id', $v['id'])->delete();

          //促销的集合和哈希的键
          $setGoodsKey = 'goods_sale_set_data';
          $hashGoodsKey = 'goods_sale_hash_data:'.$v['goods_id'];

          //删除Redis中的促销
          Redis::sRem($setGoodsKey, $hashGoodsKey);
          Redis::del($hashGoodsKey);

          //判断是否是热销商品
          $good = Goods::find($v['goods_id']);
          if ($good->buy_num < 100) {

            //商品属性的集合
            $setColorKey = 'goods_set_color_data:'.$v['goods_id'];
            $setSizeKey = 'goods_set_size_data:'.$v['goods_id'];

            //删除其在Redis的商品属性
            Redis::del($setColorKey);
            Redis::del($setSizeKey);

            //商品图片的集合
            $setPicKey = 'goods_set_pic_data:'.$v['goods_id'];

            //删除其在Redis的图片
            Redis::del($setPicKey);
          }
          
        }
      }
      
      //查询促销表的商品的最后结束时间
      $end_time = DB::table('shop_goods_sales')->select('end_time')->max('end_time');

      //最后时间 - 当前时间 = 剩余时间
      $time = strtotime($end_time) - time();


   		return view('Home.goods-sale', ['sate' => $sate, 'types' => $types, 'sales' => $sales, 'linksArray' => $linksArray, 'time' => $time, 'HotSearch' => $Hotsearch]);
   	}

}
